import 'package:flutter/services.dart';

class BluetoothService {
  static const MethodChannel _channel = MethodChannel(
    'com.example.myapp/bluetooth',
  );

  static Function(BluetoothDevice)? _onDeviceFound;
  static Function()? _onDiscoveryStarted;
  static Function()? _onDiscoveryFinished;

  /// 设置通道监听器
  static void setupChannelListener() {
    _channel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'onDeviceFound':
          final deviceData = call.arguments as Map<dynamic, dynamic>;
          final device = BluetoothDevice.fromMap(deviceData);
          _onDeviceFound?.call(device);
          break;
        case 'onDiscoveryStarted':
          _onDiscoveryStarted?.call();
          break;
        case 'onDiscoveryFinished':
          _onDiscoveryFinished?.call();
          break;
      }
    });
  }

  /// 设置设备发现回调
  static void setOnDeviceFound(Function(BluetoothDevice) callback) {
    _onDeviceFound = callback;
  }

  /// 设置扫描开始回调
  static void setOnDiscoveryStarted(Function() callback) {
    _onDiscoveryStarted = callback;
  }

  /// 设置扫描完成回调
  static void setOnDiscoveryFinished(Function() callback) {
    _onDiscoveryFinished = callback;
  }

  /// 检查蓝牙是否可用
  static Future<bool> isBluetoothAvailable() async {
    try {
      final bool result = await _channel.invokeMethod('isBluetoothAvailable');
      return result;
    } on PlatformException catch (e) {
      print('检查蓝牙可用性失败: ${e.message}');
      rethrow;
    }
  }

  /// 检查蓝牙是否启用
  static Future<bool> isBluetoothEnabled() async {
    try {
      final bool result = await _channel.invokeMethod('isBluetoothEnabled');
      return result;
    } on PlatformException catch (e) {
      print('检查蓝牙状态失败: ${e.message}');
      rethrow;
    }
  }

  /// 启用蓝牙
  static Future<bool> enableBluetooth() async {
    try {
      final bool result = await _channel.invokeMethod('enableBluetooth');
      return result;
    } on PlatformException catch (e) {
      print('启用蓝牙失败: ${e.message}');
      rethrow;
    }
  }

  /// 检查蓝牙权限
  static Future<bool> checkBluetoothPermissions() async {
    try {
      final bool result = await _channel.invokeMethod(
        'checkBluetoothPermissions',
      );
      return result;
    } on PlatformException catch (e) {
      print('检查蓝牙权限失败: ${e.message}');
      rethrow;
    }
  }

  /// 请求蓝牙权限
  static Future<bool> requestBluetoothPermissions() async {
    try {
      final bool result = await _channel.invokeMethod(
        'requestBluetoothPermissions',
      );
      return result;
    } on PlatformException catch (e) {
      print('请求蓝牙权限失败: ${e.message}');
      rethrow;
    }
  }

  /// 获取已配对设备
  static Future<List<BluetoothDevice>> getPairedDevices() async {
    try {
      final List<dynamic> result = await _channel.invokeMethod(
        'getPairedDevices',
      );
      return result.map((device) => BluetoothDevice.fromMap(device)).toList();
    } on PlatformException catch (e) {
      print('获取配对设备失败: ${e.message}');
      rethrow;
    }
  }

  /// 获取发现的设备
  static Future<List<BluetoothDevice>> getDiscoveredDevices() async {
    try {
      final List<dynamic> result = await _channel.invokeMethod(
        'getDiscoveredDevices',
      );
      return result.map((device) => BluetoothDevice.fromMap(device)).toList();
    } on PlatformException catch (e) {
      print('获取发现的设备失败: ${e.message}');
      rethrow;
    }
  }

  /// 配对设备
  static Future<bool> pairDevice(String address) async {
    try {
      final bool result = await _channel.invokeMethod('pairDevice', {
        'address': address,
      });
      return result;
    } on PlatformException catch (e) {
      print('配对设备失败: ${e.message}');
      rethrow;
    }
  }

  /// 开始扫描设备
  static Future<bool> startScan() async {
    try {
      final bool result = await _channel.invokeMethod('startScan');
      return result;
    } on PlatformException catch (e) {
      print('开始扫描失败: ${e.message}');
      rethrow;
    }
  }

  /// 停止扫描设备
  static Future<bool> stopScan() async {
    try {
      final bool result = await _channel.invokeMethod('stopScan');
      return result;
    } on PlatformException catch (e) {
      print('停止扫描失败: ${e.message}');
      rethrow;
    }
  }

  /// 连接设备
  static Future<bool> connectDevice(String address) async {
    try {
      final bool result = await _channel.invokeMethod('connectDevice', {
        'address': address,
      });
      return result;
    } on PlatformException catch (e) {
      print('连接设备失败: ${e.message}');
      rethrow;
    }
  }

  /// 断开连接
  static Future<bool> disconnect() async {
    try {
      final bool result = await _channel.invokeMethod('disconnect');
      return result;
    } on PlatformException catch (e) {
      print('断开连接失败: ${e.message}');
      rethrow;
    }
  }

  /// 发送数据
  static Future<bool> sendData(String data) async {
    try {
      final bool result = await _channel.invokeMethod('sendData', {
        'data': data,
      });
      return result;
    } on PlatformException catch (e) {
      print('发送数据失败: ${e.message}');
      rethrow;
    }
  }

  /// 读取数据
  static Future<String> readData() async {
    try {
      final String result = await _channel.invokeMethod('readData');
      return result;
    } on PlatformException catch (e) {
      print('读取数据失败: ${e.message}');
      rethrow;
    }
  }

  /// 获取连接状态
  static Future<String> getConnectionState() async {
    try {
      final String result = await _channel.invokeMethod('getConnectionState');
      return result;
    } on PlatformException catch (e) {
      print('获取连接状态失败: ${e.message}');
      rethrow;
    }
  }
}

class BluetoothDevice {
  final String name;
  final String address;
  final String type;

  BluetoothDevice({
    required this.name,
    required this.address,
    required this.type,
  });

  factory BluetoothDevice.fromMap(Map<dynamic, dynamic> map) {
    return BluetoothDevice(
      name: map['name'] ?? '未知设备',
      address: map['address'] ?? '',
      type: map['type'] ?? 'UNKNOWN',
    );
  }

  Map<String, dynamic> toMap() {
    return {'name': name, 'address': address, 'type': type};
  }
}
